package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbowen.way.config.AppConfig;
import com.zbowen.way.utils.ResultUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class DriveWayJob_2 {

    private static Logger logger = LoggerFactory.getLogger(DriveWayJob_2.class);

    private static String[] fields = new String[]{"name", "duration", "distance", "restriction", "tolls", "lights", "strategy", "road", "record"};

    @Autowired
    private DataSource dataSource;


    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("driveWayJobHandler2")
    public void driveWayJobHandler() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        logger.info(date + "：执行了driveWayJobHandler");
        // 获取默认配置的 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //  创建请求配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间
                .setConnectTimeout(Timeout.of(3000, TimeUnit.MILLISECONDS))
                // 设置响应超时时间
                .setResponseTimeout(3000, TimeUnit.MILLISECONDS)
                // 设置从连接池获取链接的超时时间
                .setConnectionRequestTimeout(3000, TimeUnit.MILLISECONDS)
                .build();

        // 起点经纬度 料坑新村 石岩
        String origin =  "113.892136,22.669206";
        // 终点经纬度 豪威科技大厦
        String destination = "113.952339,22.533434"; //"113.95249,22.533516";


        Map<String, String> params = new HashMap<>();
        params.put("key", AppConfig.key);
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("strategy", "12");
        params.put("province", URLEncoder.encode("粤", "utf-8"));
        params.put("number", "BGB2887");
        params.put("cartype", "2");
        params.put("nosteps", "0");
        params.put("extensions", "all");



        StringBuilder sb = new StringBuilder();
        sb.append(AppConfig.url_1).append("?1=1");
        params.forEach((key, value) -> {
            sb.append("&").append(key).append("=").append(value);
        });

        // 创建 GET 请求对象
        HttpGet httpGet = new HttpGet(sb.toString());
        // 设置请求参数
        httpGet.setConfig(requestConfig);
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取请求状态
        int code = response.getCode();
        if (code == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            List<Map<String, Object>> list = ResultUtils.print2(result, "牛湾新村");

            String sql = "INSERT INTO zbw_way_info (name, duration, distance, restriction, tolls, lights, strategy, road, record) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
            Connection conn = dataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql);

            for (Map<String, Object> map : list) {
                map.put("record", date);
                for (int i = 0; i < fields.length; i++) {
                    pstmt.setObject(i + 1, map.get(fields[i]));
                }
                pstmt.executeUpdate();
            }
            conn.close();
        }
    }

}
